import { logger } from '@roasmax/logger'
import { useEntityManager } from '../storage/data-source'
import { WeiboData, User, Task } from '../storage/entities'

export class TaskDataManager {
  /**
   * 获取微博数据统计信息
   */
  async getWeiboDataStats(): Promise<{
    total: number
    today: number
    thisWeek: number
    thisMonth: number
    totalUsers: number
    totalTasks: number
    avgInteractions: number
    topKeywords: Array<{ keyword: string; count: number }>
  }> {
    logger.debug('获取微博数据统计信息')

    return await useEntityManager(async m => {
      const weiboRepo = m.getRepository(WeiboData)
      const taskRepo = m.getRepository(Task)

      // 获取总数
      const total = await weiboRepo.count()

      // 获取今日数据
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      const todayCount = await weiboRepo
        .createQueryBuilder('weibo')
        .where('weibo.createdAt >= :today', { today })
        .getCount()

      // 获取本周数据
      const thisWeek = new Date()
      thisWeek.setDate(thisWeek.getDate() - thisWeek.getDay())
      thisWeek.setHours(0, 0, 0, 0)
      const thisWeekCount = await weiboRepo
        .createQueryBuilder('weibo')
        .where('weibo.createdAt >= :thisWeek', { thisWeek })
        .getCount()

      // 获取本月数据
      const thisMonth = new Date()
      thisMonth.setDate(1)
      thisMonth.setHours(0, 0, 0, 0)
      const thisMonthCount = await weiboRepo
        .createQueryBuilder('weibo')
        .where('weibo.createdAt >= :thisMonth', { thisMonth })
        .getCount()

      // 获取唯一用户数
      const uniqueUsers = await weiboRepo
        .createQueryBuilder('weibo')
        .select('COUNT(DISTINCT weibo.userId)', 'count')
        .getRawOne()

      // 获取关联任务数
      const totalTasks = await taskRepo.count()

      // 计算平均互动数
      const avgInteractionsResult = await weiboRepo
        .createQueryBuilder('weibo')
        .select('AVG(weibo.repostsCount + weibo.commentsCount + weibo.likesCount)', 'avg')
        .getRawOne()

      // 获取热门关键字（简化实现）
      const topKeywords: Array<{ keyword: string; count: number }> = []

      return {
        total,
        today: todayCount,
        thisWeek: thisWeekCount,
        thisMonth: thisMonthCount,
        totalUsers: parseInt(uniqueUsers?.count || '0'),
        totalTasks,
        avgInteractions: Math.round(parseFloat(avgInteractionsResult?.avg || '0')),
        topKeywords
      }
    })
  }

  /**
   * 获取微博数据列表
   */
  async getWeiboDataList(params: {
    page: number
    pageSize: number
    keyword?: string
    filterType?: 'all' | 'original' | 'repost'
    sortBy?: 'createdAt' | 'publishedAt' | 'interactions'
    sortOrder?: 'asc' | 'desc'
  }): Promise<{
    data: any[]
    total: number
    page: number
    pageSize: number
  }> {
    logger.debug('获取微博数据列表', params)

    return await useEntityManager(async m => {
      const weiboRepo = m.getRepository(WeiboData)
      let queryBuilder = weiboRepo.createQueryBuilder('weibo')

      // 关键字搜索
      if (params.keyword) {
        queryBuilder = queryBuilder.where('weibo.text LIKE :keyword', {
          keyword: `%${params.keyword}%`
        })
      }

      // 类型筛选
      if (params.filterType === 'original') {
        queryBuilder = queryBuilder.andWhere('weibo.isRepost = :isRepost', { isRepost: false })
      } else if (params.filterType === 'repost') {
        queryBuilder = queryBuilder.andWhere('weibo.isRepost = :isRepost', { isRepost: true })
      }

      // 排序
      const sortBy = params.sortBy || 'createdAt'
      const sortOrder = params.sortOrder || 'desc'

      if (sortBy === 'interactions') {
        queryBuilder = queryBuilder.orderBy(
          'weibo.repostsCount + weibo.commentsCount + weibo.likesCount',
          sortOrder.toUpperCase() as 'ASC' | 'DESC'
        )
      } else {
        queryBuilder = queryBuilder.orderBy(
          `weibo.${sortBy}`,
          sortOrder.toUpperCase() as 'ASC' | 'DESC'
        )
      }

      // 分页
      const offset = (params.page - 1) * params.pageSize
      queryBuilder = queryBuilder.skip(offset).take(params.pageSize)

      // 执行查询
      const [data, total] = await queryBuilder.getManyAndCount()

      return {
        data: data.map(item => item.toWeiboDataFormat()),
        total,
        page: params.page,
        pageSize: params.pageSize
      }
    })
  }

  /**
   * 获取用户数据统计信息
   */
  async getUserDataStats(): Promise<{
    total: number
    today: number
    thisWeek: number
    thisMonth: number
    vipUsers: number
    verifiedUsers: number
    avgFollowers: number
    topUsers: Array<{ nickname: string; followersCount: number }>
  }> {
    logger.debug('获取用户数据统计信息')

    return await useEntityManager(async m => {
      const userRepo = m.getRepository(User)

      // 获取总数
      const total = await userRepo.count()

      // 获取今日数据
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      const todayCount = await userRepo
        .createQueryBuilder('user')
        .where('user.createdAt >= :today', { today })
        .getCount()

      // 获取本周数据
      const thisWeek = new Date()
      thisWeek.setDate(thisWeek.getDate() - thisWeek.getDay())
      thisWeek.setHours(0, 0, 0, 0)
      const thisWeekCount = await userRepo
        .createQueryBuilder('user')
        .where('user.createdAt >= :thisWeek', { thisWeek })
        .getCount()

      // 获取本月数据
      const thisMonth = new Date()
      thisMonth.setDate(1)
      thisMonth.setHours(0, 0, 0, 0)
      const thisMonthCount = await userRepo
        .createQueryBuilder('user')
        .where('user.createdAt >= :thisMonth', { thisMonth })
        .getCount()

      // 获取VIP用户数
      const vipUsers = await userRepo.count({
        where: { isVip: true }
      })

      // 获取认证用户数
      const verifiedUsers = await userRepo
        .createQueryBuilder('user')
        .where('user.verifiedType IS NOT NULL')
        .getCount()

      // 计算平均粉丝数
      const avgFollowersResult = await userRepo
        .createQueryBuilder('user')
        .select('AVG(user.followersCount)', 'avg')
        .where('user.followersCount IS NOT NULL')
        .getRawOne()

      // 获取粉丝数最多的用户（前5名）
      const topUsers = await userRepo
        .createQueryBuilder('user')
        .select(['user.nickname', 'user.followersCount'])
        .where('user.followersCount IS NOT NULL')
        .orderBy('user.followersCount', 'DESC')
        .limit(5)
        .getRawMany()

      return {
        total,
        today: todayCount,
        thisWeek: thisWeekCount,
        thisMonth: thisMonthCount,
        vipUsers,
        verifiedUsers,
        avgFollowers: Math.round(parseFloat(avgFollowersResult?.avg || '0')),
        topUsers: topUsers.map(u => ({
          nickname: u.user_nickname,
          followersCount: u.user_followersCount
        }))
      }
    })
  }

  /**
   * 获取用户数据列表
   */
  async getUserDataList(params: {
    page: number
    pageSize: number
    keyword?: string
    filterType?: 'all' | 'vip' | 'verified' | 'normal'
    sortBy?: 'createdAt' | 'followersCount' | 'statusesCount'
    sortOrder?: 'asc' | 'desc'
  }): Promise<{
    data: any[]
    total: number
    page: number
    pageSize: number
  }> {
    logger.debug('获取用户数据列表', params)

    return await useEntityManager(async m => {
      const userRepo = m.getRepository(User)
      let queryBuilder = userRepo.createQueryBuilder('user')

      // 关键字搜索
      if (params.keyword) {
        queryBuilder = queryBuilder.where('user.nickname LIKE :keyword', {
          keyword: `%${params.keyword}%`
        })
      }

      // 类型筛选
      if (params.filterType === 'vip') {
        queryBuilder = queryBuilder.andWhere('user.isVip = :isVip', { isVip: true })
      } else if (params.filterType === 'verified') {
        queryBuilder = queryBuilder.andWhere('user.verifiedType IS NOT NULL')
      } else if (params.filterType === 'normal') {
        queryBuilder = queryBuilder.andWhere('user.isVip = :isVip', { isVip: false })
          .andWhere('user.verifiedType IS NULL')
      }

      // 排序
      const sortBy = params.sortBy || 'createdAt'
      const sortOrder = params.sortOrder || 'desc'

      queryBuilder = queryBuilder.orderBy(
        `user.${sortBy}`,
        sortOrder.toUpperCase() as 'ASC' | 'DESC'
      )

      // 分页
      const offset = (params.page - 1) * params.pageSize
      queryBuilder = queryBuilder.skip(offset).take(params.pageSize)

      // 执行查询
      const [data, total] = await queryBuilder.getManyAndCount()

      return {
        data: data.map(item => item.toUserDataFormat()),
        total,
        page: params.page,
        pageSize: params.pageSize
      }
    })
  }

  /**
   * 调试方法：检查数据库中的用户数据
   */
  async debugUserData(): Promise<void> {
    logger.info('开始检查数据库中的用户数据')

    await useEntityManager(async m => {
      const userRepo = m.getRepository(User)

      // 获取前10个用户的详细信息
      const users = await userRepo.find({
        take: 10,
        order: { createdAt: 'DESC' }
      })

      logger.info('数据库中的用户数据样本', {
        totalUsers: users.length,
        users: users.map(user => ({
          uid: user.uid,
          nickname: user.nickname,
          followersCount: user.followersCount,
          followingCount: user.followingCount,
          statusesCount: user.statusesCount,
          isVip: user.isVip,
          verifiedType: user.verifiedType,
          createdAt: user.createdAt
        }))
      })

      // 统计有粉丝数据的用户
      const usersWithFollowers = await userRepo
        .createQueryBuilder('user')
        .where('user.followersCount IS NOT NULL')
        .getCount()

      const usersWithStatuses = await userRepo
        .createQueryBuilder('user')
        .where('user.statusesCount IS NOT NULL')
        .getCount()

      logger.info('用户数据统计', {
        totalUsers: await userRepo.count(),
        usersWithFollowers,
        usersWithStatuses
      })
    })
  }
}
